<script>
import pagination from '@/utils/pagination'
import { deepCopy } from '@/utils'
export default {
  name: 'Table',
  components: {},
  inheritAttrs: false,
  props: {
    data: {
      type: Array,
      default: () => []
    },
    filterFun: {
      // 筛选数据的条件
      type: Function,
      default: undefined
    }
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 16,
      total: 0,
      pageSizes: [16, 32, 48, 64, 80],
      tableData: []
    }
  },
  watch: {
    data() {
      this.currentPage = 1
      this.currentPageChangeHandle(1)
    }
  },
  created() {
    this.currentPageChangeHandle(1)
  },
  methods: {
    currentPageChangeHandle(v) {
      this.currentPage = v
      const pd = pagination(this.filterData(), v, this.pageSize)
      this.tableData = pd.data
      this.total = pd.total
      this.$emit('data-change', this.tableData)
    },
    sizeChangeHandle(v) {
      this.pageSize = v
      const pd = pagination(this.filterData(), this.currentPage, v)
      this.tableData = pd.data
      this.total = pd.total
      this.$emit('data-change', this.tableData)
    },
    filterData() {
      if (this.filterFun instanceof Function) {
        return this.filterFun(deepCopy(this.data)) || []
      }
      return deepCopy(this.data)
    }
  },
  render(h) {
    const body = this.$scopedSlots.body
    const def = this.$scopedSlots.default
    let table = null
    if (body !== undefined) {
      table = body(this.tableData)
    } else {
      table = h(
        'el-table',
        {
          props: { data: this.tableData, ...this.$attrs },
          on: { ...this.$listeners }
        },
        def()
      )
    }
    const pag = h('el-pagination', {
      props: {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        total: this.total,
        pageSizes: this.pageSizes,
        layout: 'total, sizes, prev, pager, next, jumper'
      },
      on: {
        'current-change': this.currentPageChangeHandle,
        'size-change': this.sizeChangeHandle
      }
    })
    const tableWrap = h('div', { class: this.$style.table }, [table])
    const pagWrap = h('div', { class: [this.$style.pagination, 'pagination-container'] }, [pag])
    return h('div', { class: this.$style.wrapContainer }, [
      h('div', { class: this.$style.wrap }, [tableWrap, pagWrap])
    ])
  }
}
</script>
<style lang="scss" module>
@import "@/styles/mixin.scss";
.wrap {
  .table {
  }
  .pagination {
    @include flex($justify: flex-end);
    // padding: 10px;
  }
}
.wrapContainer {
  // & [class*="el-pager"] {
  //   & li[class*="active"] {
  //     min-width: 28px !important;
  //     border-radius: 50% !important;
  //     background-color: #3dc094;
  //     color: #fff;
  //     font-weight: normal;
  //     height: 28px !important;
  //     width: 28px !important;
  //     line-height: 28px;
  //     box-sizing: border-box !important;
  //   }
  // }
}
</style>
